package agh.io.xmlCommunicator {
	import agh.io.model.ResultEvent;

	/**
	 * @author endq
	 */
	public class XmlParser {
		
		public static function ReplaceAll(searchStr : String,replaceStr : String,origStr : String) : String {
			if (origStr.indexOf(searchStr) != -1)
			origStr = origStr.replace(searchStr, replaceStr);

			if (origStr.indexOf(searchStr) == -1)
			return origStr;
				else
			return ReplaceAll(searchStr, replaceStr, origStr);
		}
		
		public static function ParseResponse(searchStr : String) : Array {
			var s:String = searchStr;//"<events><event><name>Orofar</name><description>Lek przeciw zapaleniu gardla.</description><value>25</value><categores></categores><tags><tag>tabletki</tag><tag>syrop</tag></tags><eventlocation><eventlocation_id>2</eventlocation_id><name>Apteka MAX</name><adress>Plac szczepanski 12</adress><city></city><location></location><x>23</x><y>890</y><description></description><marker></marker></eventlocation></event></events>";
			var array:Array = new Array();
			var xml : XML = new XML(s);
			//trace(xml);	
			for each(var item:XML in xml.elements("event")) {
				for each(var itemLocation:XML in item.elements()) {
					var locationId:String = itemLocation.elements("eventlocation_id");
					var locationName:String = itemLocation.elements("name");
					var locationAdress:String = itemLocation.elements("adress");
					var x:String = itemLocation.elements("x");
					var y:String = itemLocation.elements("y");	
					//trace(locationName);				
				}
				var exist: Boolean = false;
				for each(var re:ResultEvent in array) {
					if(re.locationId == parseInt(locationId)){
						exist = true;
					}
				}
				if(!exist){
					array.push(new ResultEvent(locationName, locationAdress, parseFloat(x), parseFloat(y), parseInt(locationId)));
				}
			}
			trace(array.length);	
			return array;
		}		
		
		public static function GeneratePointXml(x:Number, y:Number) : String {
			var s:String = "<" + "location" + ">";
	 		s += "<" + "x" + ">" + x + "</" + "x" + ">";
	 		s += "<" + "y" + ">" + y + "</" + "y" + ">";
	 		s += "</" + "location" + ">";
	 		return s;
		}
				
	}
}
